package com.rzico.sbl.ui.statistic

import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityStockSupplyModifyBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.StockSupply
import com.rzico.sbl.other.showSupplyBarrelDialog
import com.rzico.sbl.other.showSupplyMoneyDialog
import com.rzico.sbl.viewmodel.StatisticStockViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.showActionDialog
import com.xinnuo.common_ui.utils.showListDialog
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class StockSupplyModifyActivity : BaseActivity(R.layout.activity_stock_supply_modify) {

    private val mBinding by lazy { ActivityStockSupplyModifyBinding.bind(getRootView()) }

    private lateinit var mEditMode: String
    private val mBrandList = ArrayList<FilterData>()
    private var mSupplyId = ""
    private var mSupplyName = ""

    override fun getViewModel() = get<StatisticStockViewModel>()

    override fun initData() {
        initTitle(title = intent.getExtra("title"))

        when (mEditMode) {
            "add" -> {
                mBinding.supplyArrearLl.gone()
                mBinding.supplySave.text = "确认添加"
            }

            "edit" -> setSupply(intent.getParcelableExtra("bean"))
        }

        getData()
    }

    override fun initListener() {
        mEditMode = intent.getExtra("mode")

        mBinding.apply {
            supplyMoneyLl.oneClick {
                showActionDialog(
                    "加欠款", "减欠款", "修改明细"
                ) { index, _ ->
                    lifecycleScope.launch {
                        delay(350)

                        when (index) {
                            0 -> mSupplyId.notEmpty { increaseMoney() }
                            1 -> mSupplyId.notEmpty { decreaseMoney() }
                            2 -> startActivityEx<StockSupplyRecordActivity>(
                                "supplyId" to mSupplyId,
                                "type" to "0"
                            )
                        }
                    }
                }
            }

            supplyBarrelLl.oneClick {
                showActionDialog(
                    "加欠桶", "减欠桶", "修改明细"
                ) { index, _ ->
                    lifecycleScope.launch {
                        delay(350)

                        when (index) {
                            0 -> mSupplyId.notEmpty {
                                mBrandList.isEmpty()
                                    .condition {
                                        showToast("获取品牌类型失败，请返回重试")
                                        return@launch
                                    }

                                increaseBarrel()
                            }
                            1 -> mSupplyId.notEmpty {
                                mBrandList.isEmpty()
                                    .condition {
                                        showToast("获取品牌类型失败，请返回重试")
                                        return@launch
                                    }

                                decreaseBarrel()
                            }
                            2 -> startActivityEx<StockSupplyRecordActivity>(
                                "supplyId" to mSupplyId,
                                "type" to "1"
                            )
                        }
                    }
                }
            }

            supplySave.oneClick {
                supplyName
                    .textTrim
                    .isEmpty()
                    .condition {
                        showToast("请输入供应商名称")
                        supplyName.requestFocus()
                        return@oneClick
                    }

                getViewModel()
                    .request(
                        requestUrl = conditionIf(
                            mEditMode == "add",
                            BaseUrl.supAdd,
                            BaseUrl.supUpdate
                        ),
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mSupplyId,
                            "name" to supplyName.textTrim,
                            "code" to supplyCode.textTrim,
                            "url" to supplyUrl.textTrim
                        ),
                        onSuccess = {
                            when (mEditMode) {
                                "add" -> showToast("添加供应商成功！")
                                "edit" -> showToast("供应商修改成功！")
                            }

                            // 刷新供应商列表
                            LiveEventBus
                                .get("supplyList")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }
    }

    /**
     * 增加欠款
     */
    private fun increaseMoney() {
        showSupplyMoneyDialog(
            name = mSupplyName,
            type = 1,
            onSure = { num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.supArrear,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mSupplyId,
                            "type" to 0,
                            "action" to 0,
                            "cash" to num,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("欠款修改成功！")

                            JSONObject(it)
                                .optNotNull("arrears")
                                .apply {
                                    mBinding
                                        .supplyMoney
                                        .text = formatDecimal()
                                }

                            // 刷新供应商列表
                            LiveEventBus
                                .get("supplyList")
                                .post("refresh")
                        }
                    )
            }
        )
    }

    /**
     * 减少欠款
     */
    private fun decreaseMoney() {
        showSupplyMoneyDialog(
            name = mSupplyName,
            type = 2,
            onSure = { num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.supArrear,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mSupplyId,
                            "type" to 0,
                            "action" to 1,
                            "cash" to num,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("欠款修改成功！")

                            JSONObject(it)
                                .optNotNull("arrears")
                                .apply {
                                    mBinding
                                        .supplyMoney
                                        .text = formatDecimal()
                                }

                            // 刷新供应商列表
                            LiveEventBus
                                .get("supplyList")
                                .post("refresh")
                        }
                    )
            }
        )
    }

    /**
     * 增加欠桶
     */
    private fun increaseBarrel() {
        showSupplyBarrelDialog(
            name = mSupplyName,
            type = 1,
            onSelect = { view, arr ->
                mPosition = 0

                showListDialog(
                    title = "请选择品牌",
                    items = mBrandList.map { it.name },
                    index = mPosition,
                    listener = { index, hint ->
                        mPosition = index
                        view.text = hint
                        arr[0] = mBrandList[index].id
                    }
                )
            },
            onSure = { barrel, num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.supArrear,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mSupplyId,
                            "type" to 1,
                            "action" to 0,
                            "barrelId" to barrel,
                            "quantity" to num,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("欠桶修改成功！")

                            JSONObject(it)
                                .optNotNull("arrearsQuantity")
                                .apply {
                                    mBinding
                                        .supplyBarrel
                                        .text = this
                                }

                            // 刷新供应商列表
                            LiveEventBus
                                .get("supplyList")
                                .post("refresh")
                        }
                    )
            }
        )
    }

    /**
     * 减少欠桶
     */
    private fun decreaseBarrel() {
        showSupplyBarrelDialog(
            name = mSupplyName,
            type = 2,
            onSelect = { view, arr ->
                mPosition = 0

                showListDialog(
                    title = "请选择品牌",
                    items = mBrandList.map { it.name },
                    index = mPosition,
                    listener = { index, hint ->
                        mPosition = index
                        view.text = hint
                        arr[0] = mBrandList[index].id
                    }
                )
            },
            onSure = { barrel, num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.supArrear,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mSupplyId,
                            "type" to 1,
                            "action" to 1,
                            "barrelId" to barrel,
                            "quantity" to num,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("欠桶修改成功！")

                            JSONObject(it)
                                .optNotNull("arrearsQuantity")
                                .apply {
                                    mBinding
                                        .supplyBarrel
                                        .text = this
                                }

                            // 刷新供应商列表
                            LiveEventBus
                                .get("supplyList")
                                .post("refresh")
                        }
                    )
            }
        )
    }

    /**
     * 店铺初始数据
     */
    private fun setSupply(bean: StockSupply?) {
        bean?.let {
            mBinding.apply {
                mSupplyId = it.id
                mSupplyName = it.name

                supplyName.setText(mSupplyName)
                supplyCode.setText(it.code.orEmpty())
                supplyUrl.setText(it.url.orEmpty())
                supplyMoney.text = it.arrears.formatDecimal()
                supplyBarrel.text = it.arrearsQuantity.orEmpty("0")

                supplyName.setSelection(supplyName.text.length)
            }
        }
    }

    /**
     * 品牌类型列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .requestCommon(
                isLoading = true,
                requestUrl = BaseUrl.bucketPdt,
                requestMethod = HttpMethod.GET,
                onSuccess = { list ->
                    mBrandList.clear()
                    list.notEmpty {
                        mapTo(mBrandList) {
                            FilterData(
                                id = it.id,
                                name = it.name.orEmpty()
                            )
                        }
                    }
                }
            )
    }

}